<script setup lang="ts">
import Dialog from '@/components/Dialog/index.vue'
import { onMounted, ref } from 'vue'

interface ButtonOption {
  text: string
  type?: 'primary' | 'default'
  onClick?: () => void
}

interface DialogOptions {
  title?: string
  content?: string
  contentTitle?: string
  contentSubTitle?: string
  buttons?: ButtonOption[]
  onClose?: () => void
}

const dialogRef = ref<InstanceType<typeof Dialog> | null>(null)
const options = ref<DialogOptions>({})
const eventChannel = ref<any>(null)

// 处理按钮点击
function handleButtonClick(onClick?: () => void) {
  // 执行按钮回调
  onClick?.()

  // 关闭对话框
  dialogRef.value?.close()

  // 延迟关闭页面，给动画一些时间
  setTimeout(() => {
    // 触发关闭事件
    eventChannel.value?.emit('close')
    // 返回上一页
    uni.navigateBack()
  }, 300)
}

// 处理按钮配置
function processButtons(buttons?: ButtonOption[]) {
  if (!buttons || buttons.length === 0) {
    return [{
      text: '确定',
      type: 'primary',
      onClick: () => handleButtonClick(),
    }]
  }

  return buttons.map(btn => ({
    ...btn,
    onClick: () => handleButtonClick(btn.onClick),
  }))
}

onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any

  eventChannel.value = currentPage.getOpenerEventChannel()

  // 监听参数传递
  eventChannel.value.on('dialogOptions', (data: DialogOptions) => {
    options.value = {
      ...data,
      buttons: processButtons(data.buttons) as any,
    }

    // 打开对话框
    setTimeout(() => {
      dialogRef.value?.open()
    }, 10)
  })
})
</script>

<template>
  <Dialog
    ref="dialogRef"
    :title="options.title"
    :buttons="options.buttons || []"
  >
    <!-- 内容标题 -->
    <template v-if="options.contentTitle" #content-title>
      {{ options.contentTitle }}
    </template>

    <!-- 内容副标题 -->
    <template v-if="options.contentSubTitle" #content-sub-title>
      {{ options.contentSubTitle }}
    </template>

    <!-- 默认内容 -->
    <view v-if="options.content">
      {{ options.content }}
    </view>
  </Dialog>
</template>

<style lang="scss" scoped>
// 页面样式透明，只显示弹窗
page {
  background-color: transparent;
}
</style>
